<?php
declare (strict_types=1);

namespace app\api\controller\v1;

use app\api\helpers\v1\traits\FileUpload;
use app\api\helpers\v1\traits\WeekDay;
use app\api\model\v1\Admins;
use app\api\model\v1\OnlineUnitDetail;
use app\api\model\v1\OnlineUnitMonth;
use app\api\model\v1\OnlineUnitYears;
use app\api\model\v1\ProgramPlan;
use app\api\model\v1\SystemConfig;
use app\api\model\v1\Users;
use app\BaseController;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use think\facade\Db;
use think\Request;

class Program extends BaseController
{
    use FileUpload, WeekDay;

    /**
     * @User: 刘海龙
     * @Date: 2021/8/26
     * @Time: 14:48
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取本月的上线单位
     */
    public function getTheMonthProgramList()
    {
        $limit = $this->request->param('limit', 10);


//        $res = OnlineUnitYears::where(['years' => date('Y')])->find();
//        if (is_null($res)) {
//            return $this->response(403, '暂未找到该年份');
        //->where(['online_unit_years_id' => $res->id])
//        }
        if (is_null($this->request->uid)) {
            $user = Users::find($this->request->wx_user_id);
            $unit_id = $user->unit_id;
        } else {
            $user = Admins::find($this->request->uid);
            $unit_id = $user->enter_unit_id;
        }
        $map = [];
        $BeginDate = date('Y-m-01', strtotime(date("Y-m-d")));
        $EndDate = date('Y-m-d', strtotime("$BeginDate +2 month -1 day"));
        if ($this->request->has('unit_title') && !empty($this->request->param('unit_title'))) {
            $map[] = ['detail_title', 'like', '%' . $this->request->param('unit_title') . '%'];
        }

        if ($this->request->has('year') && is_numeric($this->request->param('year'))) {
            $year = $this->request->param('year');
            $yesr = OnlineUnitYears::where(['years' => $this->request->param('year')])->find();
            $map[] = ['online_unit_years_id', '=', $yesr['id']];
            $BeginDate = $year . "-01-01";
            $EndDate = $year . "-12-31";
        }

        if ($this->request->param('week') == 1) {
            $week = get_week();
            $map[] = array('online_date', 'in', $week);
        }
        $detail = '';
        if (!is_null($user)) {
            if (intval($unit_id !== 0)) {
//                $BeginDate = date('Y-m-01', strtotime(date("Y-m-d")));
//                $EndDate = date('Y-m-d', strtotime("$BeginDate +2 month -1 day"));
                $detail = OnlineUnitDetail::with(['programPlan'])->whereBetweenTime('online_date', $BeginDate, $EndDate)->where($map)->paginate($limit)->each(function ($item, $key) {
                    if (empty($item['programPlan']) && $item['online_status'] === OnlineUnitDetail::ONLINE_STATUS_ONE) { //预案为空并且可以上传预案的
                        $item['is_plan'] = 0;
                        $item['is_delete'] = 0;
                    } else if (empty($item['programPlan']) && $item['online_status'] === OnlineUnitDetail::ONLINE_STATUS_TWO) { ////预案为空并且当前的状态为回复版
                        $item['is_plan'] = 1;
                        $item['is_delete'] = 0;
                    } else if (empty($item['programPlan']) && $item['online_status'] === OnlineUnitDetail::ONLINE_STATUS_THREE) { ////预案为空并且当前的状态为不上线
                        $item['is_plan'] = 2;
                        $item['is_delete'] = 0;
                    } else {
                        $item['is_plan'] = 3; //存在预案并且满足上传预案的条件
                        $item['is_delete'] = 1; //删除预案
                    }
                    return $item;
                });
            } else {
//                $BeginDate = date('Y-m-01', strtotime(date("Y-m-d")));
//                $EndDate = date('Y-m-d', strtotime("$BeginDate +2 month -1 day"));
                $detail = OnlineUnitDetail::with(['programPlan'])->whereBetweenTime('online_date', $BeginDate, $EndDate)->where($map)->paginate($limit)->each(function ($item, $key) {

                    if (empty($item['programPlan']) && $item['online_status'] === OnlineUnitDetail::ONLINE_STATUS_ONE) { //预案为空并且可以上传预案的
                        $item['is_plan'] = 0;
                        $item['is_delete'] = 0;
                    } else if (empty($item['programPlan']) && $item['online_status'] === OnlineUnitDetail::ONLINE_STATUS_TWO) { ////预案为空并且当前的状态为回复版
                        $item['is_plan'] = 1;
                        $item['is_delete'] = 0;
                    } else if (empty($item['programPlan']) && $item['online_status'] === OnlineUnitDetail::ONLINE_STATUS_THREE) { ////预案为空并且当前的状态为不上线
                        $item['is_plan'] = 2;
                        $item['is_delete'] = 0;
                    } else {
                        $item['is_plan'] = 3; //存在预案并且满足上传预案的条件
                        $item['is_delete'] = 1; //删除预案
                    }
                    return $item;
                });
            }
        }


//        if (!is_null($user)){
//            if(intval($unit_id === 0)){
//                $BeginDate = date('Y').'-'.'01-01';
//                $EndDate =  date('Y').'-'.'12-31';
//            }else{
//                $BeginDate = date('Y-m-01', strtotime(date("Y-m-d")));
//                $EndDate = date('Y-m-d', strtotime("$BeginDate +2 month -1 day"));
//
//            }
//        }else{
//            $BeginDate = date('Y').'-'.'01-01';
//            $EndDate =  date('Y').'-'.'12-31';
//        }

        return $this->response($detail);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/26
     * @Time: 16:24
     * @return \think\response\Json
     * 上传图
     */
    public function uploadImg()
    {
        if (!$this->request->file('file')) {
            return $this->response(501, '请选择上传文件');
        }
        $file = $this->request->file('file');
        $result = $this->save($file, 'program_img');
        return $this->response($result);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/26
     * @Time: 16:49
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 保存预案
     */
    public function saveProgramPlan()
    {
        $data = $this->request->param();
        $type = $this->request->param('type', 'pc');
//        $day = 3; //7天为提交期限
        //获取当前预案的上线时间
        $OnlineUnitDetail = OnlineUnitDetail::find($data['online_unit_id']);
        if (is_null($OnlineUnitDetail)) {
            return $this->response(403, '上线节目不存在');
        }
        $plan = ProgramPlan::where(['online_unit_id' => $data['online_unit_id']])->find();
        if (!is_null($plan)) {
            return $this->response(403, '预案已经存在请勿重复提交');
        }
        if ($type === 'pc') {
            $data['create_id'] = $this->request->uid;
        } else {
            $data['create_id'] = $this->request->wx_user_id;
        }
        $data['source'] = $type;
        $data['accessory_status'] = ProgramPlan::IS_STATUS_ONE;
        ProgramPlan::create($data);
//        $res = ProgramPlanUnitPivot::where(['program_plan_id' => $plan->id])->select();
//        //先删 后增
//        if (!empty($res)) {
//            foreach ($res as $key => $v) {
//                ProgramPlanUnitPivot::where(['on_unit_id' => $v['online_unit_id']])->delete();
//            }
//        }
//        ProgramPlanUnitPivot::create([
//            'program_plan_id' => $plan->id ?? 0,
//            'on_unit_id' => $data['online_unit_id'] ?? 0,
//            'en_unit_id' => $data['enter_unit_id'] ?? 0
//        ]);
        return $this->response();
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/8/30
     * @Time: 18:11
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 验证可以提前多少天提交预案权限
     */
    public function checkPlanAuth()
    {
        $id = $this->request->param('id', 0);
//        halt($id);
//        $user_type = $this->request->param('type','pc');
//        if ($user_type === 'pc'){
//            $user = Users::find($this->request->uid);
//            if ($user['enter_unit_id'] !== $id){
//                return $this->response(403, '您不属于该单位，无法上传预案');
//            }
//        }else{
//            $user = Users::find($this->request->wx_user_id);
//            if ($user['unit_id'] !== $id){
//                return $this->response(403, '您不属于该单位，无法上传预案');
//            }
//        }
        $plan = OnlineUnitDetail::find($id);
        if (is_null($plan)) {
            return $this->response(403, '暂未找到预案信息');
        }
        //1.通过配置表中获取提前预案是按照工作日还是按天
        $config_type = SystemConfig::where(['name' => 'day_type'])->find(); //获取提交类别
        $config_day = SystemConfig::where(['name' => 'day'])->find(); //获取该key等于天的
        if (is_null($config_type) && is_null($config_day)) {
            return $this->response(403, '未找到配置信息');
        }
        $day = intval($config_day->value); // 从配置表中获取天数
        $now_time = strtotime(date('Y-m-d', time())); //当前时间
        $online_date_time = strtotime($plan->online_date); //上线时间
        if (intval($config_type->value) === SystemConfig::DAY_TYPE_ONE) {
            //按天
            $time_diff = intval(($online_date_time - $now_time) / 86400);
            if ($time_diff < 0) {
                return $this->response(403, '您无法提交预案,已经超过提交日期');
            }
//            if ($time_diff > $day) {
//                return $this->response(403, "您无法提交预案,只能提前" . $day . '天');
//            }

        } else {
            //工作日
            $res = $this->getdates($online_date_time, $day);
            $return_time = strtotime($res); //返回日期
            //用当前时间对比
//            if ($online_date_time < $return_time){ //当前日期小于返回日期的时候
//                return $this->response(403, '不能提前提交');
//            }
            if ($now_time > $online_date_time) {//当前日期大于返回日期的时候
                return $this->response(403, '您无法提交预案,已经超过提交日期');
            }
        }
        return $this->response();
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/8/27
     * @Time: 8:51
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除预案
     */
    public function DelPlan($id)
    {
        $res = ProgramPlan::where(['online_unit_id' => $id])->find();
        $plan_id = $res->id;
        if (is_null($res)) {
            return $this->response(501, '预案不存在');
        }
//        ProgramPlanUnitPivot::destroy(function ($query) use ($plan_id) {
//            $query->where('program_plan_id', '=', $plan_id);
//        }, true);
        ProgramPlan::destroy(function ($query) use ($id) {
            $query->where('online_unit_id', '=', $id);
        }, true);
        return $this->response();
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/9/18
     * @Time: 19:29
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除预案微信
     */
    public function DelWXPlan()
    {
        $id = $this->request->param('id', 0);

        $res = ProgramPlan::find($id);
        if (is_null($res)) {
            return $this->response(501, '预案不存在');
        }
        ProgramPlan::destroy($id, true);
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/31
     * @Time: 15:21
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取全年上线计划
     */
    public function yearlyOnlinePlan()
    {

        $limit = $this->request->param('limit', 2);
        $res = OnlineUnitYears::where(['years' => date('Y')])->find();
        if (is_null($res)) {
            return $this->response(403, '暂无本年度数据');
        }
        $data = OnlineUnitMonth::with(['details' => function ($query) {
            $query->field('id,detail_title,online_unit_month_id,online_date,online_week,online_status');
            return $query;
        }])->field('id,month_title,online_unit_years_id')->where(['online_unit_years_id' => $res->id])->paginate($limit)->each(function ($item, $key) {
            foreach ($item['details'] as $k => $v) {
                $v['online_status_name'] = OnlineUnitDetail::$online_status[$v['online_status']] ?? '未知';
            }
            return $item;
        });
        return $this->response($data);
    }

}
